import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { storage } from '@/utils/Storage';
import { LOGIN_PATH, TOKEN_KEY } from '@/enums/commEnum';
import { useUserStoreOut } from '@/store/useUserStore';
import router from '@/router';
import { message } from 'ant-design-vue';

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    /**
     * let each request carry token
     * ['TOKEN'] is a custom headers key
     * please modify it according to the actual situation
     */
    const token = storage.get(TOKEN_KEY);
    if (token) {
      config.headers[TOKEN_KEY] = token;
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (
      !response.headers['content-type'] ||
      !response.headers['content-type'].includes('application/json')
    ) {
      return response;
    }
    const res: MyResult<any> | any = response.data;
    let userStore = useUserStoreOut();

    // if the response code is not SUCCESS, it is judged as an error.
    if (res.code !== 'SUCCESS') {
      message.error(res.message || 'Error');
      if (res.code === 'NOT_LOGIN') {
        userStore.resetToken().then(() => {
          router.push(LOGIN_PATH);
        });
      }
      return Promise.reject(new Error(res.exception || res.message));
    } else {
      return res;
    }
  },
  (error) => {
    console.error('err: ' + error); // for debug
    message.error('网络错误');
    return Promise.reject(error);
  }
);

export default class request {
  static get<T = any>(url: string, config?: AxiosRequestConfig): Promise<MyResult<T>> {
    return service.get(url, config);
  }

  static post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<MyResult<T>> {
    return service.post(url, data, config);
  }

  static put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<MyResult<T>> {
    return service.put(url, data, config);
  }

  static delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<MyResult<T>> {
    return service.delete(url, config);
  }

  static upload<T = any>(url: string, file: File, name: string = 'file'): Promise<MyResult<T>> {
    let formData = new FormData();
    formData.append(name, file);
    return service.post(url, formData);
  }

  static getBlob(url: string): Promise<AxiosResponse<Blob>> {
    return service.get(url, { responseType: 'blob' });
  }

  static postBlob(url: string, data?: any): Promise<AxiosResponse<Blob>> {
    return service.post(url, data, { responseType: 'blob' });
  }
}
